from urllib import request,parse
import json
import time

def fanyi(keyword):
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    '''定义请求的参数，并编码转换'''
    formData = {
        'i': keyword,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'sign': 'e2fd5830da31a783b6c1f83b522a7d7c',
        'doctype': 'json',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_CLICKBUTTION',
        'typoResult': 'false',

    }
    data = parse.urlencode(formData)

    '''设置headers头信息'''
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
    }

    '''创建请求，发送请求，爬取信息'''
    req = request.Request(url,data=bytes(data,encoding="utf-8"),headers=headers)
    res = request.urlopen(req)

    '''解析结果'''
    str_json = res.read().decode('utf-8')
    myjson = json.loads(str_json)
    print(myjson['translateResult'][0][0]['tgt'])

    '''防止被youdao服务器监测为恶意请求'''
    time.sleep(2)


if __name__ == "__main__":
    while True:
        keyword = input("请输入您需要翻译的内容（输入q退出）：")
        if keyword == 'q':
            break
        fanyi(keyword)
